///////////////////////
// 性能测试
#ifndef __BENCH_HPP__

#define __BENCH_HPP__

#include "../logs/log.h"
#include <chrono>
namespace Log
{
    void bench(const std::string &name, size_t thread_num, size_t msg_count, size_t msg_len)
    {
        // 获取日志器
        Logger::ptr logger = getLogger(name);
        // 创建消息,减少一个字符替换成换行
        std::string str(msg_len - 1, '1');
        // 创建线程
        size_t thread_average = msg_count / thread_num; // 平均分配给每个线程
        std::vector<std::thread> v;
        std::vector<double> allCost; // 每个线程用时存进这里
        for (int i = 1; i <= thread_num; i++)
        {
            v.emplace_back([&,i]
                           {
            //获取开始时间
            auto start = std::chrono::high_resolution_clock::now();
            for(int j=0;j<thread_average;j++)
            {
                logger->fatal("%s\n",str.c_str());
            }
            //获取结束时间
            auto end = std::chrono::high_resolution_clock::now();
            //获取总用时,单位秒
            auto cost = std::chrono::duration_cast<std::chrono::duration<double>>(end - start);
            allCost.push_back(cost.count()); });
        }
        for (auto &thr : v)
        {
            thr.join();
        }
        // 获取最大耗时作为总耗时
        double max_cost = allCost[0];
        for(int i=0;i<allCost.size();i++)
        {
            if(allCost[i]>max_cost) max_cost=allCost[i];
            printf("线程%d用时:%lf\n",i+1,allCost[i]);
        }
        // 获取每秒输出条数
        size_t per_sec_num = msg_count / max_cost;
        // 获取每秒输出,单位kb
        size_t per_sec_size = msg_count * msg_len / max_cost * 1024;
        std::cout << "测试条数:" << msg_count << "\n每条长度:" << msg_len << std::endl;
        std::cout << "测试总用时:" << max_cost << std::endl;
        std::cout << "平均每秒输出日志条数:" << per_sec_num << std::endl;
        std::cout << "平均每秒输出量:" << per_sec_size << "KB" << std::endl;
    }

    // 同步测试
    void sync_test()
    {
        GlobalBuilder build(LoggerTpye::LOGGER_SYNC);
        build.buildFormat("%m");
        build.buildLoggerName("sync");
        build.buildSink<FileSink>("./logfile/test.log");
        Logger::ptr log = build.build();
        std::cout << "同步线程性能测试\n";
        bench("sync", 3, 1000000, 100);
    }

    void async_test()
    {
        GlobalBuilder build(LoggerTpye::LOGGER_SYNC);
        build.buildFormat("%m");
        build.buildLoggerName("async");
        build.buildSink<FileSink>("./logfile/test.log");
        build.enableUnsafe();
        Logger::ptr log = build.build();
        std::cout << "异步线程性能测试\n";
        bench("async",1, 1000000, 100);
    }

}

#endif // !__BENCH_HPP__
